<template>
  <div>
    <van-form
      input-align="right"
      error-message-align="right"
      :show-error-message="false"
      show-error
      scroll-to-error
      validate-first
      @failed="onFailed"
      @submit="onSubmit"
    >
      <van-cell
        v-if="!!contentObj.inputsType || !!previousPage.inputsType"
        style="line-height: 20px; border-bottom: 1px #eee solid"
      >
        <p style="font-size: 15px">参考标准</p>
        <span style="line-height: 10px; font-size: 12px">
          {{
            identifyKey != "operationDetails"
              ? previousPage.inputsDetail
              : (!!contentObj.inputsDetail && contentObj.inputsDetail) || ""
          }}
        </span>
      </van-cell>
      <van-field
        v-if="!!contentObj.inputsType || !!previousPage.inputsType"
        readonly
        label="是否按标准执行"
        label-width="40%"
        required
        input-align="right"
      >
        <template #button>
          <div style="display: flex">
            <van-button
              :class="[flag ? '' : 'active', 'bthStyle']"
              native-type="button"
              @click="getContent(true)"
              style="margin-left: 10%"
              text="是"
              type="info"
            />
            <van-button
              :class="[flag ? 'active' : '', 'bthStyle']"
              native-type="button"
              @click="getContent(false)"
              style="margin-left: 10%"
              text="否"
              type="info"
            />
          </div>
        </template>
      </van-field>
      <van-field
        readonly
        :value="obj.stageName"
        name="stageName"
        label="阶段名称"
        placeholder="默认带出当前阶段，不可修改"
        required
        input-align="right"
      />
      <van-field
        readonly
        v-model="obj.operationName"
        name="operationName"
        label="操作名称"
        required
        placeholder="默认带出当前操作名称，不可修改"
        input-align="right"
      />
      <van-field
        readonly
        :value="obj.detectionTime"
        name="detectionTime"
        label="操作时间"
        placeholder="请选择"
        input-align="right"
        required
        @click="showPicker1 = true"
        :rules="[{ required: true, message: '请选择操作时间' }]"
      />
      <van-popup v-if="!isDisabled" v-model="showPicker1" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          @confirm="onConfirmStartDate"
          @cancel="showPicker1 = false"
        />
      </van-popup>
      <van-field
        readonly
        :value="obj.OperationOf"
        name="OperationOf"
        label="操作人"
        required
        input-align="right"
        placeholder="默认带出当前操作人，不可修改"
      />
      <van-field
        readonly
        name="siteLocation"
        label="场地"
        :value="obj.siteLocation"
        is-link
        required
        placeholder="点击多选场地"
        input-align="right"
        :rules="[{ required: true, message: '请选择场地' }]"
        @click="natureShows = true"
      />
      <van-popup v-if="!isDisabled" v-model="natureShows" position="bottom">
                 
        <van-picker
          show-toolbar
          :columns="natureNameList"
          value-key="landParcelName"
          @confirm="onConfirmType"
          @cancel="natureShows = false"
        />
               
      </van-popup>
      <van-field
        v-if="!!contentObj.inputsType || !!previousPage.inputsType"
        readonly
        name="FertilizersPesticides"
        label="肥料/农药"
        :value="obj.FertilizersPesticides"
        is-link
        required
        placeholder="点击多选肥料或农药"
        input-align="right"
        :rules="[{ required: true, message: '请选择肥料或农药' }]"
        @click="natureShow = true"
      />
      <van-popup v-if="!isDisabled" v-model="natureShow" position="bottom">
                 
        <van-picker
          show-toolbar
          :columns="natureNameLists"
          value-key="label"
          @confirm="onConfirmTypes"
          @cancel="natureShow = false"
        />
               
      </van-popup>
      <van-field
        v-model="obj.content"
        name="content"
        rows="5"
        autosize
        required
        label="操作内容"
        type="textarea"
        maxlength="200"
        input-align="left"
        placeholder="请输入说明此过程中的内容，200字以内"
        :rules="[{ required: true, message: '请输入操作内容' }]"
        show-word-limit
      />
      <div class="spacing" />
      <div
        style="background: #fff; padding: 20px"
        v-if="(!contentObj.inputsType && !previousPage.inputsType) || !flag"
      >
        <p>照片</p>
        <upload-img v-model="fileInfoList" :isDetails="false"></upload-img>
        <div class="tip">
          注：支持格式JPG、JPEG、PNG，最多上传4张照片，单个不超过5M，建议上传药剂或肥料的包装、作物实况等信息
        </div>
      </div>
      <div class="add-btn">
        <van-button
          block
          type="info"
          color="#37B5B5"
          style="width: 90%; margin: auto; margin-top: 20px"
          native-type="submit"
          size="large"
          :loading="loading"
          loading-text="提交中..."
          >保存</van-button
        >
        <!-- <van-button
          class="btn1"
          native-type="button"
          size="large"
          style="margin-top: 20px; color: #2871fe"
          @click="cancel"
          >取消</van-button
        > -->
      </div>
    </van-form>
    <!-- <div @click="onSubmit">baocun</div> -->
    <!-- <van-popup v-model="showPicker" position="bottom">
      <van-datetime-picker v-model="currentDate" type="date" @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>
    <van-popup v-model="showPicker1" class="radio-select" closeable safe-area-inset-bottom close-on-popstate	lazy-render position="bottom">
      <div style="height: 40px;text-align: center;line-height: 40px;font-size: 16px">选择产品加工批次</div>
      <yly-checkbox-list v-if="showPicker1" search-key="productProcessingBatch" :params="{queryType: 'personal',detectionFlag: 0}" :get-data-list="dataList" radio-name="productProcessingBatch" @on-change="setOrderHandle">
        <template v-slot="{object}">
          <div class="title">
            {{ object.productProcessingBatch }}
          </div>
          <div class="txt">
            产品名称：{{ object.productName }}
          </div>
          <div class="txt">
            加工时间：{{ object.processingTime|dateFormat('YYYY-MM-DD') }}
          </div>
          <div class="txt">
            加工数量(kg)：{{ object.processingNumber }}
          </div>
        </template>
      </yly-checkbox-list>
    </van-popup> -->
    <!-- 取消弹框 -->
    <!-- <van-dialog
      v-model="show"
      title="退出确认"
      show-cancel-button
      message="资料尚未提交，是否取消编辑？"
      @confirm="quit"
    /> -->
  </div>
</template>
<script>
import {
  Form,
  Field,
  Calendar,
  RadioGroup,
  Radio,
  Dialog,
  Toast,
  DatetimePicker,
  Picker,
  Button,
  Icon,
  Popup,
  Cell,
} from "vant";
// import YlyUploader from "@/components/YlyUploader";
import UploadImg from "@/components/uploadImg";
import dayjs from "dayjs";
import { getValue, setValue } from "@/utils/auth";
import { getHandle, postHandle } from "../../api";
export default {
  components: {
    UploadImg,
    [Form.name]: Form,
    [Field.name]: Field,
    [Calendar.name]: Calendar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Picker.name]: Picker,
    [DatetimePicker.name]: DatetimePicker,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Toast.name]: Toast,
    [Cell.name]: Cell,
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      contentList: "",
      fileInfoList: [],
      currentDate: new Date(),
      showPicker1: false,
      loading: false,
      flag: true,
      //   typeList: [],
      //   resultList: [],
      isDisabled: false,
      natureShows: false,
      natureNameList: [],
      siteList: [],
      natureShow: false,
      natureNameLists: [],
      fertiliList: [],
      obj: {
        stageName: null,
        operationName: null,
        detectionTime: null,
        OperationOf: null,
        siteLocation: null,
        FertilizersPesticides: null,
        content: null,
      },
      contentObj: {},
      identifyKey: getValue("keys") || "",
      productBatchId: getValue("productBatchId") || "",
      type: null,
      previousPage: {
        loginUserId: null,
        tenantCode: null,
        token: null,
        inputsType: null,
        inputsDetail: null,
        type: null,
        productionBatchStageName: null,
        name: null,
        loginName: null,
        productBatchId: null,
      },
    };
  },
  created() {
    this.$bridge.register(
      "getData",
      (
        loginUserId,
        tenantCode,
        token,
        productBatchId,
        name,
        inputsType,
        inputsDetail,
        loginName,
        productionBatchStageName,
        type
      ) => {
        this.obj.stageName = productionBatchStageName || "";
        this.obj.operationName = name || "";
        this.obj.OperationOf = loginName || "";
        this.obj.detectionTime = dayjs().format("YYYY-MM-DD");
        this.previousPage.inputsType = inputsType || "";
        this.previousPage.inputsDetail = inputsDetail || "";
        this.previousPage.productBatchId = productBatchId || "";
        this.previousPage.tenantCode = tenantCode || "";
        this.previousPage.loginUserId = loginUserId || "";
        this.previousPage.type = type || "";
        setValue("allToken", token);
        if (this.previousPage.type == "add") {
          this.identifyKey = type;
        } else {
          let id = getValue("idear");
          this.initialize(id);
        }
        this.getStandardize();
      }
    );
  },
  mounted() {
    // this.$bridge.register('getData',(data)=>{
    //   this.previousPage = JSON.parse(data)
    // })
    console.log(this.identifyKey, 777);
  },
  methods: {
    //地块和化肥农药查询
    getStandardize() {
      getHandle("/ccyt/api/bzh/landParcelInfo/queryList", {
        tenantCode: this.previousPage.tenantCode,
        loginUserId: this.previousPage.loginUserId,
      }).then((res) => {
        this.natureNameList = res.data.rows;
      });
      let identifyCode =
        this.identifyKey != "operationDetails"
          ? this.previousPage.inputsType == "化肥"
            ? "001"
            : "002"
          : this.contentObj.inputsType == "化肥"
          ? "001"
          : "002";

      getHandle("/ccyt/api/bzh/chemicalPurchase/queryBuyList", {
        tenantCode: this.previousPage.tenantCode,
        loginUserId: this.previousPage.loginUserId,
        identifyCode,
      }).then((res) => {
        console.log(res);
        this.natureNameLists = res.data.rows;
      });
    },
    //获取默认数据
    initialize(id) {
      getHandle(
        `/ccyt/api/bzh/farmOperation/queryDetail/${id}?loginUserId=${this.previousPage.loginUserId}&tenantCode=${this.previousPage.tenantCode}`
      ).then((res) => {
        this.contentObj = res.data;
        this.obj.stageName = res.data.stage;
        this.obj.operationName = res.data.operation;
        this.obj.detectionTime = dayjs(res.data.operationDate).format(
          "YYYY-MM-DD"
        );
        this.obj.OperationOf = res.data.operationUserInfoName;
        this.obj.siteLocation = res.data.places;
        this.obj.FertilizersPesticides =
          (!!res.data.inputName && res.data.inputName) || "";
        this.obj.content =
          !!res.data.inputsType && this.isStandardEnforcement == "YES"
            ? "按标准执行"
            : res.data.operationContent;
        this.fileInfoList =  res.data.operationImgs.split(",");
        this.flag = res.data.isStandardEnforcement == "NO" ? false : true;
      });
    },
    getContent(e) {
      this.flag = e;
      if (e) {
        this.contentList = this.obj.content;
        this.obj.content = "按标准执行";
      } else {
        this.obj.content = this.contentList;
      }
    },
    onConfirmStartDate(value) {
      this.obj.detectionTime = dayjs(value).format("YYYY-MM-DD");
      this.showPicker1 = false;
    },
    //肥料或农药
    onConfirmTypes(value) {
      let index = this.fertiliList.indexOf(value);
      if (index == -1) {
        this.fertiliList.push(value);
      } else {
        this.fertiliList.splice(index, 1);
      }
      this.obj.FertilizersPesticides = this.fertiliList
        .map((item) => item.label)
        .join(",");
      this.natureShow = false;
    },
    //场地选择
    onConfirmType(value) {
      let index = this.siteList.indexOf(value);
      if (index == -1) {
        this.siteList.push(value);
      } else {
        this.siteList.splice(index, 1);
      }
      this.obj.siteLocation = this.siteList
        .map((item) => item.landParcelName)
        .join(",");
      this.natureShows = false;
    },
    onFailed(errorInfo) {
      Toast(errorInfo.errors[0].message);
    },
    onSubmit(value) {
      this.loading = true;
      // let imgInfos = this.obj.imgInfos.map((item) => item.url).join(",");
      let imgInfos = [];
      // if (
      //   this.fileInfoList.length > 0 &&
      //   this.identifyKey != "operationDetails"
      // ) {
        this.fileInfoList.map((item) => {
          let data = item.url.replace(process.env.VUE_APP_FILE_SERVER_API, "");
          imgInfos.push(data);
        });
      // }else{
      //   imgInfos = this.fileInfoList
      // }
      let data = {
        productBatchInfoId:
          this.identifyKey != "operationDetails"
            ? this.previousPage.productBatchId
            : this.productBatchId,
        loginUserId: this.previousPage.loginUserId,
        tenantCode: this.previousPage.tenantCode,
        stage: value.stageName,
        operation: value.operationName,
        operationDate: value.detectionTime,
        operationContent: value.content,
        inputName:
          (!!value.FertilizersPesticides && value.FertilizersPesticides) || "",
        isStandardEnforcement: this.flag ? "YES" : "NO",
        places: value.siteLocation,
        inputsType:
          this.identifyKey == "operationDetails"
            ? this.contentObj.inputsType
            : this.previousPage.inputsType,
        inputsDetail:
          this.identifyKey == "operationDetails"
            ? this.contentObj.inputsDetail
            : this.previousPage.inputsDetail,
        operationImgs: imgInfos.join(","),
      };

      if (this.identifyKey == "operationDetails") {
        postHandle(
          `/ccyt/api/bzh/farmOperation/update/${this.contentObj.id}?loginUserId=${this.previousPage.loginUserId}&tenantCode=${this.previousPage.tenantCode}`,
          data
        ).then((res) => {
          if (res.status == "0") {
            this.$toast(res.msg);
            this.$bridge.call("base.closePage");
          } else {
            this.$toast(res.msg);
          }
          console.log(res, 888);
          setTimeout(() => {
            this.loading = false;
          }, 1000);
        });
      } else {
        postHandle(
          `/ccyt/api/bzh/farmOperation/save?loginUserId=${this.previousPage.loginUserId}&tenantCode=${this.previousPage.tenantCode}`,
          data
        ).then((res) => {
          if (res.status == "0") {
            this.$toast(res.msg);
            this.$bridge.call("base.closePage");
          } else {
            this.$toast(res.msg);
          }
          setTimeout(() => {
            this.loading = false;
          }, 1000);
        });
      }

      //   let handle = null;
      //   if (this.obj.id) {
      //     handle = productInspectionManagementService.update(
      //       this.obj,
      //       this.obj.id
      //     );
      //   } else {
      //     handle = productInspectionManagementService.save(this.obj);
      //   }
      //   handle
      //     .then((res) => {
      //       this.loading = false;
      //       Toast.success("操作成功");
      //       this.quit();
      //     })
      //     .catch(() => {
      //       this.loading = false;
      //     });
    },
  },
};
</script>
<style lang="scss" scoped>
.tip {
  padding-top: 15px;
  color: #999999;
  font-size: 12px;
  line-height: 16px;
  margin: auto;
}
.btn {
  width: 80%;
  margin: 50px auto 0 auto;
}
.btn > div {
  height: 50px;
  background: #2871fe;
  border-radius: 4px;
  text-align: center;
  line-height: 50px;
  color: #ffffff;
  font-size: 17px;
}
.btn .cancel {
  margin-top: 20px;
  background: rgba(40, 113, 254, 0.1);
  border: 1px solid #2871fe;
  color: #2871fe;
}
::v-deep .van-field__label {
  width: 6em;
}
.bthStyle {
  width: 56px;
  height: 20px;
  border-radius: 10px;
  border: 1px solid #2871fe;
}
.active {
  background-color: #fff;
  color: #2871fe;
}
.add-btn {
  padding-bottom: 20px;
}
</style>
